package org.example.study.udp;

import org.junit.Test;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

public class UDP {

    @Test
    public void sender() throws IOException {
        InetAddress localHost = InetAddress.getLocalHost();
        String str = "我是UDP方式发送的数据";
        byte[] bytes = str.getBytes();
        DatagramPacket datagramPacket = new DatagramPacket(bytes, 0, bytes.length, localHost, 8899);
        DatagramSocket datagramSocket = new DatagramSocket();
        datagramSocket.send(datagramPacket);

        datagramSocket.close();
    }

    @Test
    public  void receiver() throws IOException {
        DatagramSocket datagramSocket = new DatagramSocket(8899);

        byte[] buffer = new byte[1024];
        DatagramPacket datagramPacket = new DatagramPacket(buffer, 0, buffer.length);
        datagramSocket.receive(datagramPacket);
        System.out.println(new String(datagramPacket.getData(), 0, datagramPacket.getLength()));

        datagramSocket.close();
    }
}
